package com.gin.kotlin.gf2gamecommunity.base.composable

import androidx.compose.foundation.interaction.collectIsDraggedAsState
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.pager.rememberPagerState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch

/**
 * 横向轮播图，带页数指示器及自动滚动
 * @param T 数据类型
 * @param data 数据列表
 * @param indicatorConfig 页数指示器配置
 * @param autoScrollDuration 自动滚动的间隔，设置为0则不滚动
 * @param item 渲染单个轮播图的方法
 */
@Composable
fun <T> HorizontalCarousel(
    data: List<T>,
    indicatorConfig: IndicatorConfig = IndicatorConfig(),
    autoScrollDuration: Long = 5000L,
    item: @Composable (T) -> Unit
) {
    val pagerState = rememberPagerState(pageCount = { data.size })

    // 自动滚动
    if (autoScrollDuration > 0) {
        val isDragged by pagerState.interactionSource.collectIsDraggedAsState()
        // 当用户未操作时，才执行自动滚动
        if (isDragged.not()) {
            with(pagerState) {
                var currentPageKey by remember { mutableIntStateOf(0) }
                LaunchedEffect(key1 = currentPageKey) {
                    launch {
                        delay(timeMillis = autoScrollDuration)
                        val nextPage = (currentPage + 1).mod(pageCount)
                        animateScrollToPage(page = nextPage)
                        currentPageKey = nextPage
                    }
                }
            }
        }
    }

    HorizontalPagerWithIndicator(data = data,
        indicatorConfig = indicatorConfig,
        pagerState = pagerState,
        modifier = Modifier.fillMaxWidth(),
        item = item)
}
